<?php

/**
 * MongoDB数据库操作类
 */
class DB
{
  private $manager;
  private $username='root';
  private $password='legend';
  private $port='27017';
  private $bulk;
  private $writeConcern;
  function __construct()
  {
    // $this->manager = new MongoDB\Driver\Manager("mongodb://{$this->username}:{$this->password}@mongodb:{$this->port}");
    $this->manager = new MongoDB\Driver\Manager("mongodb://mongodb:{$this->port}");
    $this->bulk = new MongoDB\Driver\BulkWrite;
    $this->writeConcern = new MongoDB\Driver\WriteConcern(MongoDB\Driver\WriteConcern::MAJORITY, 1000);//可选，修改确认
  }

  public function query($collection,$queryArray)
  {
    $query = new MongoDB\Driver\Query($queryArray);
    return $this->manager->executeQuery($collection, $query);
  }

  public function insert($collection,$insertArray)
  {
    $bulk = new MongoDB\Driver\BulkWrite;
    $bulk->insert($insertArray);
    return $this->manager->executeBulkWrite($collection, $bulk, $this->writeConcern);
  }

  public function update($collection,$whereArray,$setArray)
  {
    $bulk = new MongoDB\Driver\BulkWrite;
    $bulk->update($whereArray,['$set' => $setArray]);
    return $this->manager->executeBulkWrite($collection, $bulk, $this->writeConcern);
  }

  public function delete($collection,$whereArray)
  {
    $bulk = new MongoDB\Driver\BulkWrite;
    $bulk->delete($whereArray);
    return $this->manager->executeBulkWrite($collection, $bulk, $this->writeConcern);
  }
}
